package com.lemo.service;

import com.lemo.bean.Person;
import com.lemo.dao.PersonDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.lang.annotation.Annotation;

@Service
public class PersonServiceImpl implements PersonService {


    private static final Logger logger = LoggerFactory.getLogger(PersonServiceImpl.class);

    @Autowired
    PersonDao personDao;

    @Override
    @CachePut(value = "person", key = "#person.id")
    public Person save(Person person) {
        Person record = personDao.save(person);
        logger.info("\n[@CachePut缓存新增的或更新的数据到缓存，" +
                "其中缓存名称为person，数据的key是person的id][{}]", record.getId());
        return record;
    }

    @Override
    @CacheEvict(value = "person")
    public void remove(Long id) {
        personDao.delete(id);
        logger.info("\n[@CacheEvict从缓存person中删除key为id的数据][{}]", id);
    }

    /**
     * http://localhost:8080/able?id=1
     *
     * @param person
     * @return
     */
    @Override
    @Cacheable(value = "person", key = "#person.id")
    public Person findOne(Person person) {
        Person one = personDao.findOne(person.getId());
        logger.info("\n[@Cacheable缓存key为person的id数据到缓存person中，" +
                "如果没有指定key,则方法参数作为key保存到缓存中][{}]", person.getId());
        return one;
    }
}
